package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementQueryObject;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.sun.jna.platform.win32.Winspool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class StatementServiceImpl implements IStatementService {

    @Autowired
    private StatementMapper statementMapper;

    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<Statement>(statementMapper.selectForList(qo));
    }


    @Override
    public void save(Statement statement) {
        statementMapper.insert(statement);
    }

    @Override
    public Statement get(Long id) {
        return statementMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(Statement statement) {
        Statement oldStatement = this.get(statement.getId());
        if (Statement.STATUS_PAID.equals(oldStatement.getStatus())) {
            throw new BusinessException("已经支付，无法进行编辑");
        }
        statementMapper.updateByPrimaryKey(statement);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            Statement statement = this.get(dictId);
            if (!Statement.STATUS_CONSUME.equals(statement.getStatus())) {
                throw new BusinessException("只有消费中的才可以删除!");
            }
            statementMapper.deleteStatementItem(dictId);
            statementMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<Statement> list() {
        return statementMapper.selectAll();
    }

    @Override
    public void saveItems(List<StatementItem> item) {
        StatementItem statementItem = item.remove(item.size() - 1);
        // 获取折扣价格
        BigDecimal discountPrice = statementItem.getItemPrice();
        Statement statement = this.get(statementItem.getStatementId());
        // 判断状态是否已经支付，没有支付才可以进行保存
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("已经支付，无法进行保存");
        }

        // 删除中间表
        statementItemMapper.deleteItemsByStatementId(statement.getId());

        // 定义总金额
        BigDecimal totalAmount = new BigDecimal(0);
        // 定义总数量
        BigDecimal totalQuantity = new BigDecimal(0);
        if (item.size()> 0) {
            for (StatementItem sItem : item) {
                statementItemMapper.insert(sItem);
                totalAmount = totalAmount.add(sItem.getItemPrice().multiply(sItem.getItemQuantity()));
                totalQuantity = totalAmount.add(sItem.getItemQuantity());
            }
        }

        if (totalAmount.compareTo(discountPrice) < 0) {
            throw new BusinessException("想霸王餐是不是，无法进行保存");
        }

        statementMapper.updateAmount(statement.getId(),totalAmount,totalQuantity,discountPrice);


    }

    @Override
    public void payStatement(Long statementId) {
        // 判读是否消费中
        Statement statement = this.get(statementId);
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("已经支付，还想给钱");
        }

        Long userId = ShiroUtils.getUserId();
        statementMapper.payStatement(statementId,userId,Statement.STATUS_PAID,new Date());
    }

    @Override
    public Long generateStatement(Long appointmentId) {
        // 判断该预约单，有没有到点或者结算单生成中，其他不可以
        Appointment appointment = appointmentMapper.selectByPrimaryKey(appointmentId);
        if (!(Appointment.STATUS_ARRIVAL.equals(appointment.getStatus()) || Appointment.STATUS_SETTLE.equals(appointment.getStatus()))) {
            throw new BusinessException("只有到点或者结算单生成才可以查看结算单");
        }

        // 判断是否已经生成结算单
        Statement statement = statementMapper.generateStatement(appointmentId);
        if (statement == null ) {
            statement = new Statement();
            statement.setCreateTime(new Date());
            statement.setActualArrivalTime(appointment.getActualArrivalTime());//实际到店时间
            statement.setCarSeries(appointment.getCarSeries());//汽车类型
            statement.setCustomerName(appointment.getCustomerName());//客户名称
            statement.setLicensePlate(appointment.getLicensePlate());//车牌号码
            statement.setAppointmentId(appointment.getId());//预约单ID
            statement.setServiceType(appointment.getServiceType().longValue());//服务类型
            statement.setCustomerPhone(appointment.getCustomerPhone());//用户联系方式
            statementMapper.insert(statement);
            appointmentMapper.changeStatus(appointmentId,Appointment.STATUS_SETTLE);// 修改状态为已经生成结算单
        }



        return statement.getId();
    }
}
